import { Exporter } from "..";

export default class JavascriptExporter implements Exporter {
    public readonly id = crypto.randomUUID()
    public readonly name = 'Javascript'
    private static readonly SUFFIX = '.js'
    private static readonly ENTRY_FILE_NAME = 'index' + JavascriptExporter.SUFFIX

    export(data: Array<TranslateTaskResult>){
        const transferMaps:Record<string, string> = {}
        const locales = data.map(item => item.locale)
        const entryFileContent = this.createEntry(locales)
        transferMaps[JavascriptExporter.ENTRY_FILE_NAME] = entryFileContent
        data.forEach(({ locale, data }) => {
            transferMaps[locale + JavascriptExporter.SUFFIX] = this.createCode(data)
        })
        return transferMaps
    };

    private createCode(data: Array<PacketData>){
        let content = 'export default {\n'
        content += '\n'
        data.forEach((item,index) => {
            content += '\t// ' + item.path + '\n'
            for(let key in item.data){
                content+= '\t' + JSON.stringify(key) + ':' + JSON.stringify(item.data[key]) + ',' + '\n'
            }
            if(index < data.length - 1) content += '\n'
        })
        content += '}'
        return content
    }

    private createEntry(locales: string[]){
        let content = ''
        for(let name of locales){
            content += `import ${name.replace('-','')} from './${name}${JavascriptExporter.SUFFIX}'\n`
        }
        content += 'export default {\n'
        for(let entry of locales){
            content+= '\t' + `"${entry}": ${entry.replace('-','')},\n`
        }
        content += '}'
        return content
    }
}